package com.qcu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qcu.dto.LoginDto;
import com.qcu.entity.StaffAccount;
import com.qcu.service.LoginService;
import com.qcu.service.StaffAccountService;
import com.qcu.util.JwtUtil;
import com.qcu.util.PasswordUtils;
import com.qcu.util.Response;
import com.qcu.util.ResponseCode;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Name: MyComputer
 * @ClassName StaffLoginServiceImpl
 * @Description:
 * @date 2025/2/7 9:53
 */
@Service("StaffLoginService")
public class StaffLoginServiceImpl implements LoginService {
    @Resource
    StaffAccountService staffAccountService;
    @Resource
    RedisTemplate redisTemplate;
    @Override
    public Response login(LoginDto loginDto) {
        LambdaQueryWrapper<StaffAccount> staffAccount = new LambdaQueryWrapper<>();
        staffAccount.eq(StaffAccount::getUsername, loginDto.getUsername());
        StaffAccount one = staffAccountService.getOne(staffAccount);
        if (one == null) {
            return Response.failure(ResponseCode.FAILURE, "用户名不存在");
        }
        if (!PasswordUtils.verifyPassword(loginDto.getPassword(), one.getSalt(), one.getPasswordHash())) {
            return Response.failure(ResponseCode.FAILURE, "密码错误");
        }
        if (!one.getRole().equals(loginDto.getType())){
            return Response.failure(ResponseCode.FAILURE, "请选择正确的类型");
        }
        Map<String,Object> claim = new HashMap<>();
        claim.put("username",one.getUsername());
        claim.put("type",one.getType());
        claim.put("id",one.getStaffId());
        claim.put("role",one.getRole());
        String token = JwtUtil.genToken(claim);
        redisTemplate.opsForValue().set(token,token,1, TimeUnit.HOURS);
        return Response.success(token);
    }
}
